<template>
    <div>
        <van-nav-bar
            title="收货地址"
            left-text="返回"
            right-text="确认"
            left-arrow
            @click-left="onClickLeft"
            @click-right="onClickRight"
        />      
        <van-address-list
            v-model="chosenAddressId"
            :list="list"
            default-tag-text="默认"
            @add="onAdd"
            @edit="onEdit"
            @select="selectEvt"
        />      
    </div>
</template>
<script>
export default {
    data() {
        return {
            list:[],
            chosenAddressId:''
        }
    },
    created() {
        this.list=this.$store.getters['common/getAddress']||[]
        this.chosenAddressId= this.list[0]?this.list[0].id:''
    },
    methods: {
        //返回
        onClickLeft(){
            this.$router.go(-1)
        },
        //确认地址,下单
        onClickRight(){
            let address=''
            for(let i=0;i<this.list.length;i++){
                if(this.list[i].id==this.chosenAddressId){
                    address=this.list[i]
                }
            }
            if(!!address){
                let arr=this.$store.getters['common/getOrderInfo']||[]
                arr.forEach(function(item){
                    item.address=address.address
                })
                let newarr=this.$store.getters['common/getMyorders']||[]
                if(newarr.length){
                    this.$store.commit('common/setMyorders',[...newarr,...arr])
                }else{
                    this.$store.commit('common/setMyorders',arr)
                }
                this.$toast.success('下单成功')
                 //下单后清除缓存的订单数据
                this.$store.commit('common/setOrderInfo',[])        
            }else{
                this.$toast({
                    message: '请选择地址',
                    position: 'bottom',
                })
            }
        },
        //添加地
        onAdd(){
            this.$router.push('/onAddAddress')
        },
        //编辑地址
        onEdit(item,index){
            sessionStorage.setItem('changeid',index)
            this.$router.push('/onEditAddress')
        },
        selectEvt(item,index){
            console.log(this.chosenAddressId)
        }
    },
}
</script>